import { defineStore } from 'pinia';
import { ref } from 'vue';
import { API_CONFIG } from '../config/apiConfig';
import router from '../router';

// 创建统一的会话过期处理方法
function handleSessionExpired() {
  // 清理用户数据
  localStorage.removeItem('userInfo');
  document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
  
  // 使用 replace 而不是 push 来防止用户通过浏览器后退返回
  router.replace('/');
}
// 定义实验室类型
export interface Lab {
  id: string;
  name: string;
  description?: string;
}

// 创建实验室请求参数
export interface CreateLabRequest {
  name: string;
  description?: string;
}

// 响应模型
interface ResponseModel<T> {
  code: number | string;
  msg: string;
  data?: T;
}

// 分页响应类型
interface PageRsp<T> {
  pageNo: string | number;
  pageSize: string | number;
  total: string | number;
  dataList: T[];
}

// 实验室响应类型
interface ResearchGroupRsp {
  id: string;
  name: string;
  description?: string;
}

export const useLabStore = defineStore('lab', () => {
  // 状态
  const labs = ref<Lab[]>([]);
  const isLoading = ref(false);
  const selectedLab = ref<Lab | null>(null);
  
  // 分页相关状态
  const pageNo = ref(1);
  const pageSize = ref(20);
  const total = ref(0);
  const hasMore = ref(true);
  const loadingMore = ref(false);

  // 获取实验室列表
  const fetchLabs = async (reset: boolean = true) => {
    if (reset) {
      pageNo.value = 1;
      labs.value = [];
      hasMore.value = true;
    }
    
    if (!hasMore.value) return true;
    
    isLoading.value = true;
    try {
      const response = await fetch(
        `${API_CONFIG.BASE_URL}/research-group/page?pageNo=${pageNo.value}&pageSize=${pageSize.value}`,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
          credentials: 'include'
        }
      );

      const result: ResponseModel<PageRsp<ResearchGroupRsp>> = await response.json();
      
      if (result.code === 0 || result.code === '0') {
        if (result.data) {
          const { dataList, total: totalCount } = result.data;
          
          // 更新总数
          total.value = Number(totalCount);
          
          // 转换并添加新数据
          const newLabs = dataList.map(item => ({
            id: item.id,
            name: item.name,
            description: item.description
          }));
          
          if (reset) {
            labs.value = newLabs;
          } else {
            labs.value = [...labs.value, ...newLabs];
          }
          
          // 检查是否还有更多数据
          hasMore.value = labs.value.length < total.value;
          
          return true;
        }
      }else if(result.code === '0001') {
        handleSessionExpired();
        return false;
      } else {
        console.error('获取实验室列表失败:', result.msg);
        return false;
      }
    } catch (error) {
      console.error('获取实验室列表请求失败:', error);
      return false;
    } finally {
      isLoading.value = false;
    }
  };

  // 加载更多实验室
  const loadMoreLabs = async () => {
    if (loadingMore.value || !hasMore.value) return;
    
    loadingMore.value = true;
    try {
      pageNo.value++;
      await fetchLabs(false);
    } finally {
      loadingMore.value = false;
    }
  };

  // 创建实验室
  const createLab = async (req: CreateLabRequest): Promise<boolean> => {
    isLoading.value = true;
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/research-group`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(req),
        credentials: 'include'
      });

      const result: ResponseModel<void> = await response.json();
      
      if (result.code === 0 || result.code === '0') {
        // 创建成功后重新获取实验室列表
        await fetchLabs();
        return true;
      } else {
        console.error('创建实验室失败:', result.msg);
        return false;
      }
    } catch (error) {
      console.error('创建实验室请求失败:', error);
      return false;
    } finally {
      isLoading.value = false;
    }
  };

  // 选择实验室
  const selectLab = (lab: Lab) => {
    selectedLab.value = lab;
  };

  // 删除实验室
  const deleteLab = async (labId: string): Promise<boolean> => {
    isLoading.value = true;
    try {
      // 调用实际的API删除实验室
      const response = await fetch(`${API_CONFIG.BASE_URL}/research-group/${labId}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include'
      });

      const result: ResponseModel<void> = await response.json();
      
      if (result.code === 0 || result.code === '0') {
        // 删除成功后从本地列表中移除
        labs.value = labs.value.filter(lab => lab.id !== labId);
        
        // 如果删除的是当前选中的实验室，清空选择
        if (selectedLab.value && selectedLab.value.id === labId) {
          selectedLab.value = null;
        }
        
        return true;
      } else {
        console.error('删除实验室失败:', result.msg);
        return false;
      }
    } catch (error) {
      console.error('删除实验室请求失败:', error);
      return false;
    } finally {
      isLoading.value = false;
    }
  };

  // 编辑实验室
  const updateLab = async (lab: Lab): Promise<boolean> => {
    isLoading.value = true;
    try {
      // 调用实际的API更新实验室
      const response = await fetch(`${API_CONFIG.BASE_URL}/research-group/${lab.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: lab.name,
          description: lab.description || ''
        }),
        credentials: 'include'
      });

      const result: ResponseModel<void> = await response.json();
      
      if (result.code === 0 || result.code === '0') {
        // 更新成功后更新本地列表
        const index = labs.value.findIndex(item => item.id === lab.id);
        if (index !== -1) {
          labs.value[index] = { ...lab };
          
          // 如果更新的是当前选中的实验室，更新选择
          if (selectedLab.value && selectedLab.value.id === lab.id) {
            selectedLab.value = { ...lab };
          }
        }
        
        return true;
      } else {
        console.error('更新实验室失败:', result.msg);
        return false;
      }
    } catch (error) {
      console.error('更新实验室请求失败:', error);
      return false;
    } finally {
      isLoading.value = false;
    }
  };

  return {
    labs,
    isLoading,
    selectedLab,
    pageNo,
    pageSize,
    total,
    hasMore,
    loadingMore,
    fetchLabs,
    loadMoreLabs,
    createLab,
    selectLab,
    deleteLab,
    updateLab
  };
});